import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:path_provider/path_provider.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';
export 'package:wechat_assets_picker/wechat_assets_picker.dart' show RequestType;
import 'package:heic_to_jpg/heic_to_jpg.dart';
import 'package:video_thumbnail/video_thumbnail.dart' as VT;
import 'package:permission_handler/permission_handler.dart';

class AssetsPickerUtil {

    ///选取图片
    static Future<List<File>> pickImages(BuildContext context,int count)async{
        List<AssetEntity>? assets = await AssetPicker.pickAssets(context,maxAssets:count,requestType: RequestType.image);
        if(assets==null)return [];
        List<File> files=[];
        for (AssetEntity item in assets) {
            bool isLocal=await item.isLocallyAvailable;
            if(!isLocal){
                SmartDialog.showLoading(msg:"从iCloud下载");
            }
            File? file=await item.originFile;
            SmartDialog.dismiss();
            if(isLocal==false&&file==null){
                SmartDialog.showToast("iCloud下载失败",alignment: Alignment.center);
            }else{
                String fileExtension = file!.path.split(".").last;
                if (fileExtension.toLowerCase() == 'heic') {
                    String? jpegPath = await HeicToJpg.convert(file.path);
                    if(jpegPath!=null){
						file = File(jpegPath);
					}
                }
                files.add(file);
            }
        }
        return files;
    }

    ///选取视频
    static Future<List<VideoFile>> pickVideo(BuildContext context,int count)async{
        List<AssetEntity>? assets = await AssetPicker.pickAssets(context,maxAssets:count,requestType: RequestType.video);
        if(assets==null)return [];
        List<VideoFile> files=[];
        for (AssetEntity item in assets) {
            bool isLocal=await item.isLocallyAvailable;
            if(!isLocal){
                SmartDialog.showLoading(msg:"从iCloud下载");
            }
            File? file=await item.originFile;
            SmartDialog.dismiss();
            if(isLocal==false&&file==null){
                SmartDialog.showToast("iCloud下载失败",alignment: Alignment.center);
            }else{

                final videoThumb = await VT.VideoThumbnail.thumbnailFile(
                    video: file!.path,
                    thumbnailPath: (await getTemporaryDirectory()).path,
                    imageFormat: VT.ImageFormat.JPEG,
                    maxWidth: 640, // specify the height of the thumbnail, let the width auto-scaled to keep the source aspect ratio
                    quality: 75,
                );
                VideoFile video=VideoFile(
                    video:file.path,
                    cover:videoThumb!
                );
                files.add(video);
            }

        }
        return files;
    }

    ///拍摄照片
    static Future<File?> pickImageFromCamera(BuildContext context) async{
        AssetEntity? entity = await CameraPicker.pickFromCamera(context,enableRecording: false);
		if(entity!=null){
			return await entity.originFile;
		}
        return null;
    }

    ///拍摄视频
    static Future<VideoFile?> pickVideoFromCamera(BuildContext context) async{
        AssetEntity? entity = await CameraPicker.pickFromCamera(context,enableRecording: true,onlyEnableRecording: true,maximumRecordingDuration: Duration(seconds: 60),textDelegate:CustomCameraPickerTextDelegateWithRecording());
        if(entity!=null){
            File? file=await entity.originFile;

            final videoThumb = await VT.VideoThumbnail.thumbnailFile(
                video: file!.path,
                thumbnailPath: (await getTemporaryDirectory()).path,
                imageFormat: VT.ImageFormat.JPEG,
                maxWidth: 640, // specify the height of the thumbnail, let the width auto-scaled to keep the source aspect ratio
                quality: 75,
            );
            VideoFile video=VideoFile(
                video:file.path,
                cover:videoThumb!
            );
            return video;
        }
        return null;
    }
}

class CustomCameraPickerTextDelegateWithRecording
    implements CameraPickerTextDelegate {
  factory CustomCameraPickerTextDelegateWithRecording() => _instance;

  CustomCameraPickerTextDelegateWithRecording._internal();

  static final CustomCameraPickerTextDelegateWithRecording _instance =
      CustomCameraPickerTextDelegateWithRecording._internal();

  @override
  String confirm = '确认';

  @override
  String shootingTips = '长按摄像';

  @override
  String loadFailed = '加载失败';
}

class VideoFile{
    String video;
    String cover;
    VideoFile(
      {required this.video,
      required this.cover});
    Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['video'] = this.video;
        data['cover'] = this.cover;
        return data;
    }
}
